﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Security.Permissions;

namespace geApp
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class geAppForm : Form
    {
        /// <summary>
        /// constructor
        /// </summary>
        public geAppForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Public Methods
        /// Called from JavaScript
        /// </summary>
 
        /// <summary>
        /// Called by initCallback()
        /// toggles the options and logs various detials
        /// </summary>
        /// <param name="earthVersion">ge.getEarthVersion()</param>
        /// <param name="pluginVersion">ge.getEarthVersion()</param>
        /// <param name="apiVersion">ge.getApiVersion()</param>
        public void geReady(string earthVersion, string pluginVersion, string apiVersion)
        {
            geIsReady = true;
            invoke_toggleGeOptions();
            invoke_toggleGeLayers();
            //
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(webBrowserGe.DocumentTitle);
            sb.AppendLine("Browser version: " + webBrowserGe.Version);
            sb.AppendLine("Earth Version: " + earthVersion);
            sb.AppendLine("Plugin Version: " + pluginVersion);
            sb.AppendLine("API Version: " + apiVersion);
            sb.AppendLine("Connected to: " + webBrowserGe.Document.Url.ToString());
            updateLog(sb.ToString());
        }

        /// <summary>
        /// Called by failureCallback()
        /// alerts the user to the error
        /// </summary>
        public void geFailed()
        {
           MessageBox.Show("The plug-in has failed to load, try pressing the refreh button", "Ge Error!");
        }

        /// <summary>
        /// Called by geEventListener()
        /// </summary>
        /// <param name="time">kmlEvent.getTimeStamp()</param>
        /// <param name="type">kmlEvent.getTarget().getType()</param>
        /// <param name="sX">kmlEvent.getScreenX()</param>
        /// <param name="sY">kmlEvent.getScreenY()</param>
        /// <param name="cX">kmlEvent.getScreenX()</param>
        /// <param name="cY">kmlEvent.getClientY()</param>
        public void geEvent(string time, string type, string sX, string sY, string cX, string cY)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(time + ": " + type + "; ");
            sb.Append(" screen x,y: " + sX + "," + sY);
            sb.Append(" client x,y: " + cX + "," + cY);
            updateLog(sb.ToString());
        }

        /// <summary>
        /// Private Methods
        /// used to invoke Javascript functions
        /// </summary>

        // This generic method is not used in the application
        private void invoke_javascript(string function, object[] args)
        {
            if (geIsReady)
            {
                webBrowserGe.Document.InvokeScript(function, args);
            }
        }

        private void invoke_toggleGeOptions()
        {
            if (geIsReady)
            {
                Object[] args = new object[] {
                    checkBoxStatusBar.Checked,
                    checkBoxGrid.Checked,
                    checkBoxOverview.Checked,
                    checkBoxScale.Checked,
                    checkBoxAtmosphere.Checked,
                    checkBoxMouseNav.Checked,
                    checkBoxNavigation.Checked
                };
                webBrowserGe.Document.InvokeScript("toggleGeOptions", args);
            }           
        }

        private void invoke_toggleGeLayers()
        {
            if (geIsReady)
            {
                Object[] args = new object[] {
                    checkBoxTerrain.Checked,
                    checkBoxRoads.Checked,
                    checkBoxBorders.Checked,
                    checkBoxBuildings.Checked
                };
                webBrowserGe.Document.InvokeScript("toggleGeLayers", args);
            }
        }

        private void invoke_loadNetworkLink(string uri)
        {
            if (geIsReady)
            {
                try
                {
                    new Uri(uri);
                }
                catch (UriFormatException)
                {
                    return;
                }
                webBrowserGe.Document.InvokeScript("loadNetworkLink", new String[] { uri });
            }
        }

        /// <summary>
        /// Private Memebers/Methods
        /// </summary>

        private Boolean geIsReady = false;

        private void geAppForm_Load(object sender, EventArgs e)
        {
            webBrowserGe.IsWebBrowserContextMenuEnabled = false;// disable the context menu
            webBrowserGe.WebBrowserShortcutsEnabled = false;// disable keyboard shortcuts
            webBrowserGe.AllowWebBrowserDrop = false;// disable drag and drop documents
            webBrowserGe.ObjectForScripting = this;// allow javascript to access this class
            webBrowserGe.Url = new Uri("http://earthapi.googlepages.com/geToCs.html");
        }

        private void updateLog(string msg)
        {
            textBoxLog.Text += msg + Environment.NewLine;
            textBoxLog.SelectionStart = textBoxLog.Text.Length;
            textBoxLog.ScrollToCaret();
            textBoxLog.Refresh();
        }

        /// <summary>
        /// GUI Event Handlers
        /// </summary>

        private void optionCheckHandler_CheckStateChanged(object sender, EventArgs e)
        {
            invoke_toggleGeOptions();
        }

        private void layerCheckHandler_CheckStateChanged(object sender, EventArgs e)
        {
            invoke_toggleGeLayers();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            webBrowserGe.Refresh(WebBrowserRefreshOption.Completely);
        }

        private void buttonProperties_Click(object sender, EventArgs e)
        {
            webBrowserGe.ShowPropertiesDialog();
 
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            invoke_loadNetworkLink(textBoxInputUrl.Text);
        }

        private void geAppForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //This will kill the geplugin instance
            //System.Diagnostics.Process[] gep =
            //    System.Diagnostics.Process.GetProcessesByName("geplugin");
            //gep[0].Kill();
        }
    }
}
